import ObsClient from "esdk-obs-browserjs";

const bucketname = "jiuren-ai-study";
const obsClient = new ObsClient({
  access_key_id: "HPUATMJLWSZGOSMBPNK4",
  secret_access_key: "3TIGZVtcn9J4076uomTDqZYOX3ljcrV3VqSjqabR",
  server: "https://obs.cn-north-4.myhuaweicloud.com",
  bucketname: "jiuren-ai-study",
});
// 生成随机文件名
export const generateUUID = () => {
  return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
// 获取文件后缀
const getFileExtension = (filename) => {
  const match = filename.match(/\.([a-zA-Z0-9]+)$/);
  return match ? match[1] : "";
}
// 判断文件是否大于100KB
export const isFileOver100KB = (file) => {
  const sizeInKB = file.size / 1024;
  return sizeInKB > 100;
}
// 小于100KB的文件直接上传
const uploadSmallFile = ({file, key, success, fail}) => {
  obsClient.putObject(
    {
      Bucket: bucketname,
      Key: key,
      SourceFile: file,
    },
    function (err, result) {
      if (err) {
        console.error("Error-->" + err);
        // _this.$emit("fail", err);
        fail(err);
      } else {
        console.log("Status-->" + result.CommonMsg.Status);
        if (result.CommonMsg.Status < 300) {
          console.log("RequestId-->" + result.InterfaceResult.RequestId);
          console.log("Bucket-->", result.InterfaceResult);
          console.log("Key-->" + result.InterfaceResult.Key);
          // const url = `${_this.baseUrl}${key}`;
          // console.log("Location-->" + url);
          // _this.$emit("success", url);
          success(key);
        } else {
          // _this.$emit("fail", result.CommonMsg.Message);
          fail(result.CommonMsg.Message);
        }
      }
    }
  );
}
const upload = ({file, key, success, fail}) => {
  let cp;
  let hook;
  obsClient.uploadFile(
    {
      Bucket: bucketname,
      Key: key,
      SourceFile: file,
      PartSize: 3 * 1024 * 1024,
      ProgressCallback: function (
        transferredAmount,
        totalAmount,
        totalSeconds
      ) {
        console.log((transferredAmount * 1.0) / totalSeconds / 1024);
        console.log((transferredAmount * 100.0) / totalAmount);
        if (hook && transferredAmount / totalAmount > 0.5) {
          // 暂停断点续传任务
          // hook.cancel();
        }
      },
      EventCallback: function (eventType, eventParam, eventResult) {
        // 处理事件响应
      },
      ResumeCallback: function (resumeHook, uploadCheckpoint) {
        // 获取取消断点续传上传任务控制参数
        hook = resumeHook;
        // 记录断点
        cp = uploadCheckpoint;
      },
    },
    function (err, result) {
      console.error("Error-->" + err);
      // 出现错误，再次调用断点续传接口，继续上传任务
      if (err) {
        obsClient.uploadFile(
          {
            UploadCheckpoint: cp,
            ProgressCallback: function (
              transferredAmount,
              totalAmount,
              totalSeconds
            ) {
              console.log((transferredAmount * 1.0) / totalSeconds / 1024);
              console.log((transferredAmount * 100.0) / totalAmount);
            },
            EventCallback: function (eventType, eventParam, eventResult) {
              // 处理事件响应
            },
          },
          function (err, result) {
            if (err) {
              console.error("Error-->" + err);
            } else {
              if (result.CommonMsg.Status < 300) {
                console.log(
                  "RequestId-->" + result.InterfaceResult.RequestId
                );
                console.log("Bucket-->" + result.InterfaceResult.Bucket);
                console.log("Key-->" + result.InterfaceResult.Key);
                console.log(
                  "Location-->" + result.InterfaceResult.Location
                );
              } else {
                console.log("Code-->" + result.CommonMsg.Code);
                console.log("Message-->" + result.CommonMsg.Message);
              }
            }
          }
        );
      } else {
        console.log("Status-->" + result.CommonMsg.Status);
        if (result.CommonMsg.Status < 300 && result.InterfaceResult) {
          console.log("RequestId-->" + result.InterfaceResult.RequestId);
          // console.log("RequestId-->", result.InterfaceResult);
          // const url = `${_this.baseUrl}${result.InterfaceResult.Key}`;
          // _this.$emit("success", url);
          success(result.InterfaceResult.Key);
        } else {
          // _this.$emit("fail", result.CommonMsg.Message);
          fail(result.CommonMsg.Message);
        }
      }
    }
  );
}
// 上传文件
export const uploadFile = ({file, success = () => {}, fail = () => {}}) => {
  const key = generateUUID() + "." + getFileExtension(file.name);
  if (isFileOver100KB(file)) {
    upload({file, key, success, fail});
  } else {
    uploadSmallFile({file, key, success, fail});
  }
}